package com.fancon.android.gardenjokesx.activity;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.entity.FacebookUser;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.social.DatabaseHelper;
import com.fancon.android.gardenjokesx.social.SocialUntil;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;

public class P063Activity extends GardenJokesBaseActivity {
	private ListView p063ListView;
	private P06SeparatedListAdapter adapter;
	private LinearLayout textList;
	private HashMap<String, Integer> alphaIndexer;
	private boolean[] listSetUser;
	private int numpost = 0;
	private EditText mEditText;
	private ArrayList<FacebookUser> listFacebookUsers;
	private ArrayList<FacebookUser> listSelectedUser;
	private FacebookUser currentFacebookUser;
	private String accessToken = "";
	private Button buttonDone;
	private Bundle bundle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.p063_layout);
		// bundle = savedInstanceState;
		initParameter();

		for (int i = 0; i <= 26; i++) {
			TextView textView;
			Character c;
			if (i < 26) {
				c = new Character((char) ('A' + i));
			} else {
				c = new Character('#');
			}
			textView = new TextView(this);
			textView.setTag(c);
			textView.setText(c.toString());
			textView.setTextColor(Color.BLACK);
			textView.setGravity(Gravity.CENTER_HORIZONTAL);
			textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
			textView.setTextSize(getResources().getDimension(
					R.dimen.p063SlideTextSize));
			textView.setLayoutParams(new LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			textList.addView(textView);
			Log.d("TAG_", "" + textView.getTextSize());
		}
		LoadFacebookFriend loadFacebookFriend = new LoadFacebookFriend(
				"LoadFriend", P063Activity.this);
		getGlobalState().getRequestQueue().addRequest(loadFacebookFriend);
		setUIEvent();
	}

	@SuppressWarnings("unchecked")
	public void initParameter() {
		alphaIndexer = new HashMap<String, Integer>();
		textList = (LinearLayout) findViewById(R.id.textList);
		mEditText = (EditText) findViewById(R.id.p063_editText);
		buttonDone = (Button) findViewById(R.id.p063_buttonDone);
		adapter = new P06SeparatedListAdapter(this);
		p063ListView = (ListView) findViewById(R.id.p063_listView);
		p063ListView.setCacheColorHint(0);
		bundle = getIntent().getExtras();

		if ((listSelectedUser = (ArrayList<FacebookUser>) bundle
				.getSerializable(Constant.LIST_FRIEND)) == null) {
			listSelectedUser = new ArrayList<FacebookUser>();
		}
		listFacebookUsers = new ArrayList<FacebookUser>();
		DatabaseHelper databaseUntil = new DatabaseHelper(
				getApplicationContext());
		User currentUser = UserUtil.getInfoUserLogin(getApplicationContext());
		currentFacebookUser = databaseUntil.getFacebookUser(currentUser
				.getUser_id());
		if (currentFacebookUser != null) {
			accessToken = currentFacebookUser.getAccessToken();
		}

	}

	public void setOnTouchListener(View v) {
		v.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_MOVE) {
					textList.setBackgroundColor(getResources().getColor(
							R.color.gray));
					int posChac = (int) ((event.getY() - 10) / 23);
					if (posChac >= 0 && posChac <= 26) {
						Character c = (char) ('A' + posChac);
						if (alphaIndexer.containsKey(c.toString())) {
							p063ListView.setSelectionFromTop(
									alphaIndexer.get(c.toString()), 0);
						}
					}
					if (event.getY() > ((23 * 26) + 10)) {
						if (alphaIndexer.containsKey("#")) {
							p063ListView.setSelectionFromTop(
									alphaIndexer.get("#"), 0);
						}
					}
					return true;
				}
				if (event.getAction() == MotionEvent.ACTION_UP) {
					textList.setBackgroundColor(getResources().getColor(
							android.R.color.transparent));
					return true;
				}
				return true;
			}
		});
	}

	public void setUIEvent() {

		setOnTouchListener(textList);

		p063ListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View item, int pos,
					long arg3) {
				try {

					View view = item.findViewById(R.id.p063_checkbox);
					if (view.isShown()) {
						view.setVisibility(View.INVISIBLE);
						FacebookUser facebookUserLocal = (FacebookUser) adapter
								.getItem(pos);
						facebookUserLocal.setChecked(false);
						listSelectedUser.remove(facebookUserLocal);
						Log.d("CurrentSize", "Current Size Unselect: "
								+ listSelectedUser.size());
					} else {
						view.setVisibility(View.VISIBLE);
						FacebookUser facebookUserLocal = (FacebookUser) adapter
								.getItem(pos);
						facebookUserLocal.setChecked(true);
						listSelectedUser.add(facebookUserLocal);
						Log.d("CurrentSize", "Current Size Select: "
								+ listSelectedUser.size());
						Log.d("Username", facebookUserLocal.getUsername());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		mEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence ex, int start, int before,
					int count) {

				if (ex.length() > 0) {
					String key = ex.toString().toUpperCase();
					ArrayList<FacebookUser> tempArrayList = new ArrayList<FacebookUser>();
					for (int i = 0; i < listFacebookUsers.size(); i++) {
						if (listFacebookUsers.get(i).getUsername()
								.toUpperCase().contains(key)) {
							tempArrayList.add(listFacebookUsers.get(i));
						}
					}
					builList(tempArrayList);
					Log.d("OK", "Build list success");
				} else {
					textList.setVisibility(View.VISIBLE);
					setOnTouchListener(textList);
					builList(listFacebookUsers);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		buttonDone.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (listSelectedUser.size() > 0) {
					for (int i = 0; i < listSelectedUser.size(); i++) {
						Log.d("User",
								"Selected user: "
										+ listSelectedUser.get(i).getUsername());
					}
					setResultForUser();
					finish();
				} else {
					setResult(RESULT_CANCELED);
					finish();
				}
			}
		});
	}

	public void setResultForUser() {
		Intent intent = this.getIntent();
		bundle.putSerializable(Constant.LIST_FRIEND, listSelectedUser);
		intent.putExtras(bundle);
		setResult(RESULT_OK, intent);
		finish();
	}

	@Override
	public void onBackPressed() {
		if (listSelectedUser.size() > 0) {
			setResultForUser();
			finish();
		} else {
			setResult(RESULT_CANCELED);
			finish();
		}
		// super.onBackPressed();
	}

	class LoadFacebookFriend extends RequestUI {

		private Activity context;
		private FanconProgressBar showProgressBar;

		public LoadFacebookFriend(Object key, Activity activity) {
			super(key, activity);
			try {
				context = activity;
				showProgressBar = FanconProgressBar.show(
						context.getParent() != null ? context.getParent()
								: context, context
								.getString(R.string.common_loading));
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}

		@Override
		public void execute() throws Exception {
			try {
				SocialUntil socialUntil = new SocialUntil(
						getApplicationContext());
				listFacebookUsers = socialUntil
						.getFriendIdsFacebook(accessToken);
				listSetUser = new boolean[listFacebookUsers.size()];
				Log.d("size", "Size : " + listFacebookUsers.size());
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}

		@Override
		public void executeUI(Exception ex) {
			try {
				builList(listFacebookUsers);
				if (showProgressBar != null) {
					showProgressBar.dismiss();
				}
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}
	}

	public void builList(ArrayList<FacebookUser> listFacebookUsers) {
		numpost = 0;
		adapter.removeAllSection();
		alphaIndexer.clear();
		if (listFacebookUsers.size() < 50) {
			textList.setVisibility(View.INVISIBLE);
		} else {
			if (!textList.isShown()) {
				textList.setVisibility(View.VISIBLE);
			}
		}
		if (listFacebookUsers != null) {
			for (int i = (int) 'A'; i < (int) 'Z'; i++) {
				ArrayList<FacebookUser> tempList = new ArrayList<FacebookUser>();

				/* Lay tat ca cac user co ten bat dau boi ki tu i */
				for (int j = 0; j < listFacebookUsers.size(); j++) {
					if (listFacebookUsers.get(j).getfirstNameFB()
							.startsWith(new Character((char) i).toString())) {
						tempList.add(listFacebookUsers.get(j));
						listSetUser[j] = true;
					}
				}
				if (tempList.size() > 0) {
					// Log.d("Chac",new Character((char) i).toString() +
					// " have " + tempList.size());
					alphaIndexer.put(new Character((char) i).toString(),
							numpost);
					numpost += tempList.size() + 1;
					Log.d("Numpos", " Numpost : " + numpost);
					P063Adapter adapter1 = new P063Adapter(tempList,
							getApplicationContext());
					adapter.addSection(new Character((char) i).toString(),
							adapter1);
				}

			}
			ArrayList<FacebookUser> tempList = new ArrayList<FacebookUser>();
			for (int i = 0; i < listFacebookUsers.size(); i++) {
				if (!listSetUser[i]) {
					tempList.add(listFacebookUsers.get(i));
				}

				/* Kiem tra nhung user nao da duoc chon */
				if (listSelectedUser.size() > 0) {
					for (int j = 0; j < listSelectedUser.size(); j++) {
						if (listFacebookUsers.get(i).equals(
								listSelectedUser.get(j))) {
							listFacebookUsers.get(i).setChecked(true);
						}
					}
				}
			}
			alphaIndexer.put(new Character((char) '#').toString(), numpost);
			numpost += tempList.size() + 1;
			P063Adapter adapter1 = new P063Adapter(tempList,
					getApplicationContext());
			adapter.addSection(new Character((char) '#').toString(), adapter1);
			p063ListView.setAdapter(adapter);
			adapter.notifyDataSetChanged();
		}
	}

}
